<!--
 * @Descripttion:
 * @version:
 * @Author: ZhangXue
 * @Date: 2021-07-12 09:17:30
 * @LastEditors: ZhangXue
 * @LastEditTime: 2021-07-13 14:26:08
-->
<template>
  <div class="fd-login-contain"></div>
</template>

<script>
import common from "@/assets/js/common/common";
import md5 from "js-md5";

export default {
  name: "login",
  data () {
    return {
      // 历史路径
      _history: "",
      // 登录表单信息
      loginForm: {
        phone: "",
        password: ""
      },
      // 验证规则
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          },
          {
            validator: common.rules.checkPassword,
            trigger: "blur"
          }
        ]
      }
    };
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      // 通过 `vm` 访问组件实例,将值传入fromPath
      vm._history = from.name;
    });
  },
  created () {},
  methods: {
    /**
     * 用户登录功能
     */
    login () {
      // 验证登录表单字段是否符合输入规则
      this.$refs["loginForm"].validate(valid => {
        if (!valid) {
          // 表单验证失败，不发送请求，直接返回，退出方法；页面会有提示
          return;
        }
        // 登录表单验证成功,发送登陆请求
        this.postLogin();
      });
    },

    /**
     * 发送登录请求
     */
    postLogin () {
      const _params = {
        phone: this.loginForm.phone,
        password: md5(this.loginForm.password)
      };
      this.$axios
        .post(this.$config.url.userApi.userLogin, _params)
        .then(res => {
          if (res.code !== 200) {
            // 如果返回的状态标识不是200 成功标识，提示请求出错,展示后端返回的错误信息，然后退出方法
            this.$message.error("登陆失败!");
            return;
          }
          // 返回状态是成功，将用户名存到sessionStorage，方便菜单展示用户名，并跳转到首页
          window.sessionStorage.setItem("username", res.data.username);
          window.sessionStorage.setItem("userId", res.data.id);
          this.$router.push("/index");
        })
        .catch(() => {
          this.$message.error("登陆失败!");
        });
    }
  }
};
</script>

<style scoped lang="less"></style>
